<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% extends 'base.html' %}

{% block title %}{{ product.drawing_no_1|default:"产品详情" }} - 小原焊枪选型数据库{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- 产品详情头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4 fade-in-up">
            <div>
                <h1 class="display-6 fw-bold">
                    <i class="bi bi-gear me-2"></i>
                    {{ product.drawing_no_1|default:"未知产品" }}
                </h1>
                <p class="lead text-muted"><!-- {{ product.description|default:"暂无描述" }}-->暂无描述</p>
            </div>
            <div>
                <a href="javascript:history.back()" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回
                </a>
            </div>
        </div>
        
        <div class="row">
            <!-- 产品图片 -->
            <div class="col-lg-4">
                <div class="card fade-in-up">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-image me-2"></i>
                            产品图片
                        </h5>
                    </div>
                    <div class="card-body text-center">
                        {% if product.bmp_file_path %}
                         <img src="{% url 'clamps:protected_media' path=product.bmp_file_path %}" 
                                 class="img-fluid rounded shadow" 
                                 onclick="previewImage('{% url 'clamps:protected_media' path=product.bmp_file_path %}', '{{ product.drawing_no_1|escapejs }}')"
                                 style="cursor: pointer; max-height: 300px;"
                                 alt="产品图片"
                                 onerror="this.src='/static/images/no-image.png'">
                            <p class="text-muted mt-2 small">点击图片放大查看</p>
                        {% else %}
                            <div class="py-5">
                                <i class="bi bi-image text-muted" style="font-size: 4rem;"></i>
                                <p class="text-muted mt-3">暂无产品图片</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- 文件下载 -->
                <div class="card mt-4 fade-in-up">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-download me-2"></i>
                            文件下载
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            {% if product.pdf_file_path %}
                                <a href="{% url 'clamps:download_file' product.id 'pdf' %}" 
                                   class="btn btn-outline-primary download-btn">
                                    <i class="bi bi-file-earmark-arrow-down me-2"></i>
                                    下载 PDF 文件
                                </a>
                            {% else %}
                                <button class="btn btn-outline-secondary" disabled>
                                    <i class="bi bi-file-earmark-x me-2"></i>
                                    PDF 文件不可用
                                </button>
                            {% endif %}
                            
                            {% if product.step_file_path %}
                                <a href="{% url 'clamps:download_file' product.id 'step' %}" 
                                   class="btn btn-outline-success download-btn">
                                    <i class="bi bi-file-earmark-arrow-down me-2"></i>
                                    下载 STEP 文件
                                </a>
                            {% else %}
                                <button class="btn btn-outline-secondary" disabled>
                                    <i class="bi bi-file-earmark-x me-2"></i>
                                    STEP 文件不可用
                                </button>
                            {% endif %}
                            
							<!--
                            {% if product.bmp_file_path %}
                                <a href="{% url 'clamps:download_file' product.id 'bmp' %}" 
                                   class="btn btn-outline-info download-btn">
                                    <i class="bi bi-file-earmark-arrow-down me-2"></i>
                                    下载 BMP 文件
                                </a>
                            {% else %}
                                <button class="btn btn-outline-secondary" disabled>
                                    <i class="bi bi-file-earmark-x me-2"></i>
                                    BMP 文件不可用
                                </button>
                            {% endif %}
                            -->
							
                            {% if product.pdf_file_path %}
                                <div class="mt-3">
                                    <button class="btn btn-outline-secondary w-100" 
                                         onclick="previewPDF('{% url 'clamps:protected_media' path=product.pdf_file_path %}', '{{ product.drawing_no_1|escapejs }}')"
                                         >
                                        <i class="bi bi-file-earmark-pdf me-2"></i>
                                        预览 PDF 文件
                                    </button>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 产品参数 -->
            <div class="col-lg-8">
                <div class="card fade-in-up">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-list-ul me-2"></i>
                            产品参数（由人工数据库手动导出，无法保证参数完全正确，仅供参考）
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- 基本信息 -->
                            <div class="col-12">
                                <h6 class="text-primary mb-3">
                                    <i class="bi bi-info-circle me-2"></i>
                                    基本信息
                                </h6>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>分类：</strong>
                                <span class="badge bg-primary">{{ product.category.name }}</span>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>子分类类型：</strong>
                                {{ product.sub_category_type|default:"--" }}
                            </div>
                            
                            <div class="col-12 mb-3">
                                <strong>描述：</strong>
								<!-- {{ product.description|default:"--" }} -->
                                暂无描述
                            </div>
                            
                            <!-- 技术参数 -->
                            <div class="col-12 mt-4">
                                <h6 class="text-primary mb-3">
                                    <i class="bi bi-gear-wide-connected me-2"></i>
                                    技术参数
                                </h6>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>行程：</strong>
                                {% if product.stroke %}{{ product.stroke }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>加压力：</strong>
                                {% if product.clamping_force %}{{ product.clamping_force }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>重量：</strong>
                                {% if product.weight %}{{ product.weight }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong class="highlight-field">喉深：</strong>
                                {% if product.throat_depth %}{{ product.throat_depth }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong class="highlight-field">喉宽：</strong>
                                {% if product.throat_width %}{{ product.throat_width }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong class="highlight-field">变压器：</strong>
                                {{ product.transformer|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>电极臂端部：</strong>
                                {{ product.electrode_arm_end|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>电极臂类型：</strong>
                                {{ product.electrode_arm_type|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>变压器放置方向：</strong>
                                {{ product.transformer_placement|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>法兰P.C.D：</strong>
                                {{ product.flange_pcd|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>有无平衡：</strong>
                                {{ product.has_balance|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>水路：</strong>
                                {{ product.water_circuit|default:"--" }}
                            </div>
                            
                            <!-- 托架和齿轮箱参数 -->
                            <div class="col-12 mt-4">
                                <h6 class="text-primary mb-3">
                                    <i class="bi bi-tools me-2"></i>
                                    托架和齿轮箱
                                </h6>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>托架方向：</strong>
                                {{ product.bracket_direction|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>托架角度：</strong>
                                {% if product.bracket_angle %}{{ product.bracket_angle }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>MOTOR厂家：</strong>
                                {{ product.motor_manufacturer|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>托架个数：</strong>
                                {% if product.bracket_count %}{{ product.bracket_count }}{% else %}--{% endif %}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>齿轮箱型式：</strong>
                                {{ product.gearbox_type|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>托架材料：</strong>
                                {{ product.bracket_material|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>齿轮箱行程：</strong>
                                {{ product.gearbox_stroke|default:"--" }}
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <strong>换枪装置：</strong>
                                {{ product.tool_changer|default:"--" }}
                            </div>
                            
                            <!-- 动态参数区域 -->
                            {% if product.category.name|stringformat:"s"|slice:"-2:" == "-C" %}
                                <!-- 偏心参数 -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-primary mb-3">
                                        <i class="bi bi-arrows-angle-contract me-2"></i>
                                        偏心参数
                                    </h6>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>偏心方向：</strong>
                                    {{ product.eccentricity_direction|default:"--" }}
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>偏心距离：</strong>
                                    {% if product.eccentricity %}{{ product.eccentricity }}{% else %}--{% endif %}
                                </div>
                            {% elif "-X" in product.category.name %}
                                <!-- 电极臂参数 -->
                                <div class="col-12 mt-4">
                                    <h6 class="text-primary mb-3">
                                        <i class="bi bi-arrows-angle-expand me-2"></i>
                                        电极臂参数
                                    </h6>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>静电极臂前部长：</strong>
                                    {% if product.static_arm_front_length %}{{ product.static_arm_front_length }}{% else %}--{% endif %}
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>静电极臂前部高：</strong>
                                    {% if product.static_arm_front_height %}{{ product.static_arm_front_height }}{% else %}--{% endif %}
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>动电极臂前部长：</strong>
                                    {% if product.moving_arm_front_length %}{{ product.moving_arm_front_length }}{% else %}--{% endif %}
                                </div>
                                <div class="col-md-6 mb-3">
                                    <strong>动电极臂前部高：</strong>
                                    {% if product.moving_arm_front_height %}{{ product.moving_arm_front_height }}{% else %}--{% endif %}
                                </div>
                            {% endif %}
                            
                            <!-- X型分类专用参数 -->
                            {% if product.static_arm_eccentricity or product.moving_arm_eccentricity %}
                                <div class="col-12 mt-4">
                                    <h6 class="text-primary mb-3">
                                        <i class="bi bi-arrows-angle-expand me-2"></i>
                                        X型分类专用参数
                                    </h6>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>静臂偏心：</strong>
                                    {% if product.static_arm_eccentricity %}{{ product.static_arm_eccentricity }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>动臂偏心：</strong>
                                    {% if product.moving_arm_eccentricity %}{{ product.moving_arm_eccentricity }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>静电极臂端部：</strong>
                                    {{ product.static_electrode_arm_end|default:"--" }}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>动电极臂端部：</strong>
                                    {{ product.moving_electrode_arm_end|default:"--" }}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>支轴到驱动中心距离：</strong>
                                    {% if product.pivot_to_drive_center_dist %}{{ product.pivot_to_drive_center_dist }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>静电极臂前部长：</strong>
                                    {% if product.static_arm_front_length %}{{ product.static_arm_front_length }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>静电极臂前部高：</strong>
                                    {% if product.static_arm_front_height %}{{ product.static_arm_front_height }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>动电极臂前部长：</strong>
                                    {% if product.moving_arm_front_length %}{{ product.moving_arm_front_length }}{% else %}--{% endif %}
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <strong>动电极臂前部高：</strong>
                                    {% if product.moving_arm_front_height %}{{ product.moving_arm_front_height }}{% else %}--{% endif %}
                                </div>
                            {% endif %}
                            
                            <!-- 其他参数 -->
                            {% if product.eccentricity_to_center or product.guidance_method or product.grip_extension_length %}
                                <div class="col-12 mt-4">
                                    <h6 class="text-primary mb-3">
                                        <i class="bi bi-plus-circle me-2"></i>
                                        其他参数
                                    </h6>
                                </div>
                                
                                {% if product.eccentricity_to_center %}
                                    <div class="col-md-6 mb-3">
                                        <strong>偏心是否回到中心面：</strong>
                                        {{ product.eccentricity_to_center }}
                                    </div>
                                {% endif %}
                                
                                {% if product.guidance_method %}
                                    <div class="col-md-6 mb-3">
                                        <strong>导向方式：</strong>
                                        {{ product.guidance_method }}
                                    </div>
                                {% endif %}
                                
                                {% if product.grip_extension_length %}
                                    <div class="col-md-6 mb-3">
                                        <strong>握杆伸出长度：</strong>
                                        {{ product.grip_extension_length }}
                                    </div>
                                {% endif %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- 创建和更新时间 -->
                <div class="card mt-4 fade-in-up">
                    <div class="card-body">
                        <div class="row text-muted small">
                            <div class="col-md-6">
                                <i class="bi bi-calendar-plus me-2"></i>
                                创建时间：{{ product.created_at|date:"Y-m-d H:i:s" }}
                            </div>
                            <div class="col-md-6">
                                <i class="bi bi-calendar-check me-2"></i>
                                更新时间：{{ product.updated_at|date:"Y-m-d H:i:s" }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% load static %}  {# 确保模板开头已加载static标签 #}

{% block extra_js %}
{# 引用本地目录的PDF.js #}
<script src="{% static 'js/pdf.js' %}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 检查本地PDF.js是否加载成功
        if (typeof pdfjsLib === 'undefined') {
            console.error('本地PDF.js加载失败，请检查/static/js/pdf.min.js是否存在');
            alert('PDF预览组件加载失败，请联系管理员');
        }
    });

    function previewPDF(pdfUrl, title) {
        if (typeof pdfjsLib === 'undefined') {
            alert('PDF预览组件未加载完成');
            return;
        }
        
        if (!pdfUrl || pdfUrl.trim() === '') {
            alert('PDF文件路径无效');
            return;
        }

        // 移除旧模态框
        const oldModal = document.getElementById('pdfPreviewModal');
        if (oldModal) oldModal.remove();
        
        // 创建新模态框
        const modal = document.createElement('div');
        modal.id = 'pdfPreviewModal';
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 9999;
            display: flex;
            flex-direction: column;
            padding: 20px;
            box-sizing: border-box;
        `;
        
        // 标题栏
        const header = document.createElement('div');
        header.style.cssText = `
            color: white;
            font-size: 18px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        `;
        header.innerHTML = `
            <span>${title || 'PDF预览'}</span>
            <button class="close-pdf-modal" style="background: #ff4444; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">
                关闭预览
            </button>
        `;
        
        // 加载提示
        const loader = document.createElement('div');
        loader.style.cssText = `
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
        `;
        loader.textContent = '正在加载PDF文件，请稍候...';
        
        // PDF容器
        const container = document.createElement('div');
        container.style.cssText = `
            flex: 1;
            overflow: auto;
            background: white;
            padding: 20px;
            border-radius: 4px;
            display: none;
        `;
        
        modal.appendChild(header);
        modal.appendChild(loader);
        modal.appendChild(container);
        document.body.appendChild(modal);
        
        // 关闭函数
        function closePreview() {
            modal.remove();
            document.removeEventListener('keydown', handleKeyDown);
        }
        
        // 关闭事件绑定
        modal.querySelector('.close-pdf-modal').addEventListener('click', closePreview);
        modal.addEventListener('click', (e) => e.target === modal && closePreview());
        
        // ESC键关闭
        function handleKeyDown(e) {
            if (e.key === 'Escape') closePreview();
        }
        document.addEventListener('keydown', handleKeyDown);
        
        // 加载PDF（使用本地配置）
pdfjsLib.GlobalWorkerOptions.workerSrc = "{% static 'js/pdf.worker.js' %}";
        const loadingTask = pdfjsLib.getDocument({
            url: pdfUrl,
            cMapUrl: "{% static 'js/cmaps/' %}",   // 本地 cmaps 目录
            cMapPacked: true
        });
        
        loadingTask.promise
            .then(function(pdf) {
                loader.style.display = 'none';
                container.style.display = 'block';
                
                // 渲染所有页面
                for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
                    pdf.getPage(pageNum).then(function(page) {
                        const scale = 1.5;
                        const viewport = page.getViewport({ scale });
                        
                        const canvas = document.createElement('canvas');
                        canvas.style.cssText = `
                            display: block;
                            margin: 0 auto 20px;
                            border: 1px solid #eee;
                            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                        `;
                        const context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;
                        
                        container.appendChild(canvas);
                        
                        // 渲染页面并添加水印
                        page.render({
                            canvasContext: context,
                            viewport: viewport
                        }).promise.then(() => {
                            addWatermark(context, viewport.width, viewport.height);
                        });
                    });
                }
            })
            .catch(function(error) {
                console.error('PDF加载失败:', error);
                loader.style.color = '#ff4444';
                loader.textContent = `加载失败: ${error.message}`;
            });
        
        // 两行水印绘制函数
function addWatermark(context, width, height) {
			const isChinese = navigator.language.startsWith("zh");
			const watermarkBase = isChinese ? "图纸仅供参考[OBARA]" : "For Reference Only[OBARA]";
			const now = new Date();
			const dateStr = now.getFullYear() + "-" + (now.getMonth() + 1).toString().padStart(2, "0") + "-" + now.getDate().toString().padStart(2, "0");
			const timeStr = now.getHours().toString().padStart(2, "0") + ":" + now.getMinutes().toString().padStart(2, "0") + ":" + now.getSeconds().toString().padStart(2, "0");
			const user = "{{ request.user.username }}"; // 获取当前登录用户名
			
			const watermarkLines = [
				watermarkBase,
				`${user}     ${dateStr} ${timeStr}`
			];
			context.save();
			context.fillStyle = 'rgba(255, 0, 0, 0.5)';
			context.font = '24px Arial, sans-serif';
			context.textAlign = 'center';
			context.textBaseline = 'middle';
			context.rotate(-Math.PI / 6); // 30度倾斜
			
			// 关键调整：增大间距避免重叠
			const lineHeight = 50; // 增大行高（两行文字垂直间距）
			const stepX = 300;     // 增大水平间距（原300→400）
			const stepY = 250;     // 增大垂直间距（原220→300）
			
			// 计算文字实际宽度（用于更精准的间距控制）
			const textWidth = Math.max(
				context.measureText(watermarkLines[0]).width,
				context.measureText(watermarkLines[1]).width
			);
			// 考虑旋转后的实际占用宽度（三角函数修正）
			const rotatedWidth = textWidth / Math.cos(Math.PI / 6);
			// 确保水平间距不小于旋转后的文字宽度
			const adjustedStepX = Math.max(stepX, rotatedWidth * 1.2);
			
			// 网格状绘制（使用调整后的间距）
			for (let x = -200; x < width + 200; x += adjustedStepX) {
				for (let y = -100; y < height + 200; y += stepY) {
					watermarkLines.forEach((line, index) => {
						// 增加每行文字的垂直偏移，避免内部重叠
						context.fillText(line, x, y + (index * lineHeight));
					});
				}
			}
			
			context.restore();
		}
    }
	
    // 下载文件时显示提示
    document.querySelectorAll('.download-btn').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const fileName = this.textContent.trim();
            const downloadUrl = this.href;
            
            // 显示提示
            showDownloadWarning(() => {
                // 3秒后开始下载
                setTimeout(() => {
                    window.location.href = downloadUrl;
                }, 3000);
            });
        });
    });
    
    function showDownloadWarning(callback) {
        const warningHtml = `
            <div class="modal fade" id="downloadWarningModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">下载提示</h5>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-warning">
                                <i class="bi bi-exclamation-triangle me-2"></i>
                                图纸模型数据由于各种原因发生变更后不另行通知，选型数据库无法保证图纸模型数据完全正确，该数据不作为任何参考依据。
                            </div>
                            <div class="text-center">
                                <div class="spinner-border text-primary me-2" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <span id="countdown">3</span> 秒后自动开始下载...<br>数据较多时服务器压缩需要时间，请耐心等待
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="directDownloadBtn">如窗口没有自动跳转点此直接下载</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        const existingModal = document.getElementById('downloadWarningModal');
        if (existingModal) {
            existingModal.remove();
        }
        
        document.body.insertAdjacentHTML('beforeend', warningHtml);
        const modal = new bootstrap.Modal(document.getElementById('downloadWarningModal'));
        
        let countdown = 3;
        const countdownElement = document.getElementById('countdown');
        const directDownloadBtn = document.getElementById('directDownloadBtn');
        
        const timer = setInterval(() => {
            countdown--;
            countdownElement.textContent = countdown;
            if (countdown <= 0) {
                clearInterval(timer);
                modal.hide();
                callback();
            }
        }, 1000);
        
        directDownloadBtn.addEventListener('click', () => {
            clearInterval(timer);
            modal.hide();
            callback();
        });
        
        modal.show();
        
        // 模态框关闭时清理定时器
        document.getElementById('downloadWarningModal').addEventListener('hidden.bs.modal', () => {
            clearInterval(timer);
            document.getElementById('downloadWarningModal').remove();
        });
    }
    
    function showToast(message, type = 'info') {
        const toastHtml = `
            <div class="toast align-items-center text-white bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        let toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
            document.body.appendChild(toastContainer);
        }
        
        toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        const toast = new bootstrap.Toast(toastContainer.lastElementChild);
        toast.show();
    }
</script>
{% endblock %}

